package org.origin.centre.security.authentication.handlers;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.origin.centre.utils.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import java.io.IOException;

/**
 * 登录认证失败处理器
 *
 * @author ferret
 * @version 2024-05-08
 */
public class IAuthenticationFailureHandler implements AuthenticationFailureHandler {
    private final static Logger logger = LoggerFactory.getLogger(IAuthenticationSuccessHandler.class);

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        if (exception instanceof OAuth2AuthenticationException) {
            OAuth2Error error = ((OAuth2AuthenticationException) exception).getError();
            logger.error("authentication login failure：{}", error.getErrorCode());
            ResponseUtil.failure(response, "请求失败：" + error.getErrorCode());
        } else {
            logger.error("authentication login failure：", exception);
            ResponseUtil.failure(response, "请求失败：" + exception.getMessage());
        }
    }

}
